/*******************************************************************************
 * Package: com.hngtrust.iir.user.controller
 * Type:    RoleController
 * Date:    2021/3/16 11:00
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.user.controller;

import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.controller.vo.OptLogReqVO;
import com.hngtrust.iir.base.service.LogService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.user.controller.dto.AddRoleUserReqVO;
import com.hngtrust.iir.user.controller.dto.EditRoleFuncReqVO;
import com.hngtrust.iir.user.controller.dto.ListRoleFuncRespVO;
import com.hngtrust.iir.user.controller.dto.RoleListUserVO;
import com.hngtrust.iir.user.controller.dto.ViewRoleVO;
import com.hngtrust.iir.user.entity.Role;
import com.hngtrust.iir.user.entity.RoleFunc;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.RoleFuncService;
import com.hngtrust.iir.user.service.RoleService;
import com.hngtrust.iir.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @author Keqiwei
 * @date 2021/3/16 11:00
 */
@Slf4j
@Api(tags = "角色管理")
@RestController
@RequestMapping("/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleFuncService roleFuncService;
    
    @Autowired
    private LogService logService;
    
    
    @Autowired
    private PageService pageService;
    /**
     *
     * 主键生成器
     */
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    @ApiOperation("角色列表")
    @PostMapping("/list-role")
    public ResponseInfo<PageResult<Role>> listRole(@ApiParam(value = "角色列表") @Valid @RequestBody ReqDTO<Object> req){
        Role role = new Role();
        PageResult<Role> page = pageService.page(req.getPageParam(), () -> roleService.queryList(role));
        return new ResponseInfo<>(page);
    }
    
    @ApiOperation("添加角色")
    @PostMapping("/add-role")
    public ResponseInfo<Object> addRole(@ApiParam(value = "角色添加") @Valid @RequestBody ViewRoleVO req){
        Role role = new Role();
        role.setName(req.getName());
        ResponseInfo<Object> data = new ResponseInfo<Object> ();
        OptLogReqVO vo = new OptLogReqVO();
        vo.setOptModule(14);
        vo.setOptType(6);
        vo.setOptContent("添加"+req.getName());
        if (roleService.queryList(role).isEmpty()) {
            BeanUtils.copyProperties(req,role);
            role.setId(myIdGenerator.nextId());
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            role.setCreateTime(new Date());
            role.setStatus(Constant.DEFAULT_STATUS_NORMAL);
            role.setCreateUserId(loginUser.getId());
            role.setUpdateUserId(loginUser.getId());
            role.setUpdateTime(new Date());
            roleService.add(role);
            vo.setStatus(1);
            logService.saveOptLog(vo);
            return data;
        }
        data.setMessage("角色名已存在");
    
        vo.setStatus(2);
        logService.saveOptLog(vo);
        return data;
    }
    
    @ApiOperation("删除角色")
    @PostMapping("/delete-role")
    public ResponseInfo<Object> deleteRole(@ApiParam(value = "角色添加") @Valid @RequestBody ViewRoleVO req){
        User user = new User();
        user.setRoleId(req.getId());
        OptLogReqVO vo = new OptLogReqVO();
        vo.setOptModule(14);
        vo.setOptType(8);
        vo.setOptContent("删除"+roleService.queryById(req.getId()).getName());
        ResponseInfo<Object> date = new ResponseInfo<Object>();
        if (userService.queryList(user).isEmpty()){
            roleFuncService.deleteByRoleId(req.getId());
            roleService.deleteById(req.getId());
            vo.setStatus(1);
            logService.saveOptLog(vo);
            date.setData("删除成功");
            return date;
        }
        vo.setStatus(2);
        logService.saveOptLog(vo);
        date.setMessage("角色已绑定用户，无法删除");
        date.setCode("1");
        return date;
    }
    
    @ApiOperation("修改角色")
    @PostMapping("/update-role")
    public ResponseInfo<Object> updateRole(@ApiParam(value = "角色修改") @Valid @RequestBody ViewRoleVO req){
        ResponseInfo<Object> date = new ResponseInfo<Object>();
        Role role = new Role();
        if(null != req.getName() && !req.getName().isEmpty()){
            role.setName(req.getName());
            List<Role> list = roleService.queryList(role);
            if(list.size() > 1){
                date.setCode("1");
                date.setMessage("角色名已存在");
                return date;
            }
            if(list.size() > 0){
                Role r = list.get(0);
                if(!r.getId().equals(req.getId())){
                    date.setCode("1");
                    date.setMessage("角色名已存在");
                    return date;
                }
            }
        }
        
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        BeanUtils.copyProperties(req,role);
        role.setUpdateUserId(loginUser.getId());
        role.setUpdateTime(new Date());
        roleService.modifyById(role);
        OptLogReqVO vo = new OptLogReqVO();
        vo.setOptModule(14);
        vo.setOptType(7);
        vo.setOptContent("修改"+roleService.queryById(req.getId()).getName());
        vo.setStatus(1);
        logService.saveOptLog(vo);
        date.setMessage("修改成功");
        return date;
    }
    
    @ApiOperation("角色用户列表")
    @PostMapping("list-role-user")
    public ResponseInfo<RoleListUserVO> listRoleUser(@ApiParam(value = "角色用户数据") @Valid @RequestBody ViewRoleVO req){
        RoleListUserVO list = new RoleListUserVO();
        list.setNoSelectUser(userService.noSelectUser(req.getId()));
        list.setSelectUser(userService.selectUser(req.getId()));
        list.setListNoSelectUser(userService.queryListNoSelectUser(req.getId()));
        User user = new User();
        user.setRoleId(req.getId());
        list.setListSelectUser(userService.queryList(user));
        return new ResponseInfo<>(list);
    }
    @ApiOperation("角色用户列表查询")
    @PostMapping("query-role-user")
    public ResponseInfo<List<User>> queryRoleUser(@ApiParam(value = "角色用户数据") @Valid @RequestBody ViewRoleVO req){
        User user = new User();
        user.setRoleId(req.getId());
        user.setName(req.getUserName());
        List<User> users = userService.queryLikeName(user);
        return new ResponseInfo<>(users);
    }
    
    @ApiOperation("添加角色用户")
    @PostMapping("add-role-user")
    public ResponseInfo<Object> addRoleUser(@ApiParam(value = "用户角色数据") @Valid @RequestBody AddRoleUserReqVO reqDTO){
        User user = new User();
        
        //先把该角色的用户清空
        userService.clearRole(reqDTO.getId());

        for (AddRoleUserReqVO.RoleUser roleUser : reqDTO.getUsers()){
            user.setId(roleUser.getUserId());
            if (roleUser.getStatus()==0){
                user.setRoleId(reqDTO.getId());
            }
            userService.modifyById(user);
        }
        OptLogReqVO vo = new OptLogReqVO();
        vo.setOptModule(14);
        vo.setOptType(9);
        vo.setOptContent("配置"+roleService.queryById(reqDTO.getId()).getName());
        vo.setStatus(1);
        logService.saveOptLog(vo);
        return new ResponseInfo<>();
    }
    
    
    @ApiOperation("角色功能列表")
    @PostMapping("/list-role-func")
    public ResponseInfo<ListRoleFuncRespVO> listRoleFunc(@ApiParam(value = "角色权限数据") @Valid @RequestBody ViewRoleVO viewRoleDTO){
        RoleFunc roleFunc = new RoleFunc();
        roleFunc.setRoleId(viewRoleDTO.getId());
        List<RoleFunc> roleFuncs = roleFuncService.queryList(roleFunc);
        List<Long> ids = roleFuncs.stream().map(r -> r.getFuncId()).collect(Collectors.toList());
        ListRoleFuncRespVO vo = new ListRoleFuncRespVO();
        vo.setIds(ids);
        return new ResponseInfo<>(vo);
    }
    
    @ApiOperation("修改角色权限")
    @PostMapping("/update-role-func")
    public ResponseInfo<Object> updateRoleFunc(@ApiParam(value = "角色权限数据") @Valid @RequestBody EditRoleFuncReqVO req){
        roleFuncService.deleteByRoleId(req.getId());
         User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        if(!req.getFuncList().isEmpty()) {
            for (Long funcId : req.getFuncList()) {
                RoleFunc roleFunc = new RoleFunc();
                roleFunc.setId(myIdGenerator.nextId());
                roleFunc.setFuncId(funcId);
                roleFunc.setRoleId(req.getId());
                roleFunc.setCreateTime(new Date());
                roleFunc.setCreateUserId(loginUser.getId());
                roleFuncService.add(roleFunc);
            }
        }
        OptLogReqVO vo = new OptLogReqVO();
        vo.setOptModule(14);
        vo.setOptType(9);
        vo.setOptContent("配置"+roleService.queryById(req.getId()).getName()+"权限");
        vo.setStatus(1);
        logService.saveOptLog(vo);
        return new ResponseInfo<>();
    }
}
